import Person from './models/Person.js';
import FamilyTree from './models/FamilyTree.js';
import PersonRelationship from './models/PersonRelationship.js';
import Common from './models/Common.js';
import { Op } from 'sequelize';

class PersonService {
    
    async getAllPersons(familyTreeId) {
        let where = {};
        if (familyTreeId) {
            where.familyTreeId = familyTreeId;
        }
        const persons = await Person.findAll({
            where,
            order: [['birthDate', 'ASC']]
        });
        // 查询所有关系一次，避免N+1
        const allRelationships = await PersonRelationship.findAll({
            paranoid: false // 包含软删除的关系记录
        });
        console.log('【调试】所有关系数据:', allRelationships.map(r => ({
            personId1: r.personId1,
            personId2: r.personId2,
            relationshipTypeId: r.relationshipTypeId
        })));
        
        // For each person, get their basic family info and calculate generation
        const personsWithRelations = await Promise.all(
            persons.map(async (person) => {
                const personJson = person.toJSON();
                // 查找父亲
                const fatherRel = allRelationships.find(r => r.personId2 === person.id && r.relationshipTypeId === 1);
                personJson.fatherId = fatherRel ? fatherRel.personId1 : null;
                // 查找母亲
                const motherRel = allRelationships.find(r => r.personId2 === person.id && r.relationshipTypeId === 4);
                personJson.motherId = motherRel ? motherRel.personId1 : null;
                // 查找养父
                const adoptedFatherRel = allRelationships.find(r => r.personId2 === person.id && r.relationshipTypeId === 2);
                personJson.adoptedFatherId = adoptedFatherRel ? adoptedFatherRel.personId1 : null;
                // 查找养母
                const adoptedMotherRel = allRelationships.find(r => r.personId2 === person.id && r.relationshipTypeId === 3);
                personJson.adoptedMotherId = adoptedMotherRel ? adoptedMotherRel.personId1 : null;
                // 查找配偶
                const spouseRel = allRelationships.find(r =>
                    (r.personId1 === person.id && r.relationshipTypeId === 5) ||
                    (r.personId2 === person.id && r.relationshipTypeId === 5)
                );
                personJson.spouseId = spouseRel
                    ? (spouseRel.personId1 === person.id ? spouseRel.personId2 : spouseRel.personId1)
                    : null;
                // Get spouse对象
                if (personJson.spouseId) {
                    const spouseObj = persons.find(p => p.id === personJson.spouseId);
                    personJson.spouse = spouseObj ? spouseObj.toJSON() : null;
                }
                // Get children count - 修复逻辑：只计算真正的子女关系
                const childrenCount = allRelationships.filter(r =>
                    r.personId1 === person.id && [8, 9, 10, 11].includes(r.relationshipTypeId) // 我是父母，对方是子女
                ).length;
                personJson.childrenCount = childrenCount;
                
                // Calculate generation
                personJson.generation = await this.calculateGeneration(person.id);
                
                // 调试输出关键人员的父母关系
                if (['王建国', '王建华', '王秀兰', '王老太爷', '王老太太'].includes(personJson.name)) {
                    console.log(`【调试】${personJson.name} (ID:${personJson.id}): 父亲=${personJson.fatherId}, 母亲=${personJson.motherId}, 养父=${personJson.adoptedFatherId}, 养母=${personJson.adoptedMotherId}, 配偶=${personJson.spouseId}`);
                }
                
                return personJson;
            })
        );
        
        // 配偶代数同步：确保配偶显示相同代数
        const personMap = new Map(personsWithRelations.map(p => [p.id, p]));
        for (const person of personsWithRelations) {
            if (person.spouseId && personMap.has(person.spouseId)) {
                const spouse = personMap.get(person.spouseId);
                // 如果配偶的代数不同，取较大的代数（更准确的代数）
                if (spouse.generation !== person.generation) {
                    const maxGeneration = Math.max(person.generation || 1, spouse.generation || 1);
                    person.generation = maxGeneration;
                    spouse.generation = maxGeneration;
                    console.log(`【调试】同步配偶代数: ${person.name} 和 ${spouse.name} 都设为第${maxGeneration}代`);
                }
            }
        }
        
        console.log('【调试】返回的人员数据数量:', personsWithRelations.length);
        return personsWithRelations;
    }

    // 计算世代
    async calculateGeneration(personId, visited = new Set()) {
        if (visited.has(personId)) return 1; // 防止循环引用
        visited.add(personId);

        // 查找父母
        const parentRelations = await PersonRelationship.findAll({
            paranoid: false, // 包含软删除的关系记录
            where: { 
                personId2: personId,
                relationshipTypeId: { [Op.in]: [1, 4] } // 父亲、母亲
            }
        });

        if (parentRelations.length === 0) {
            return 1; // 没有父母，是第一代
        }

        // 递归计算父母的世代，取最大值
        const parentGenerations = await Promise.all(
            parentRelations.map(rel => this.calculateGeneration(rel.personId1, new Set(visited)))
        );

        return Math.max(...parentGenerations) + 1;
    }

    async getPersonDetail(personId) {
        try {
            console.log(`【调试】开始获取成员详情 ID: ${personId}`);
            
            // 允许查到软删除成员
            const person = await Person.findByPk(personId, { paranoid: false });
            if (!person) {
                console.log(`【调试】成员不存在 ID: ${personId}`);
                return null;
            }
            
            console.log(`【调试】找到成员: ${person.name} (ID: ${person.id})`);
            const personJson = person.toJSON();

            // 1. 父母 (Correctly finds people who are parents OF this person)
            console.log(`【调试】开始查询父母关系`);
            const parentRelations = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: {
                    personId2: personId,
                    relationshipTypeId: { [Op.in]: [1, 2, 3, 4] } // 1:父亲, 2:养父, 3:养母, 4:母亲
                },
                include: [
                    {
                        model: Person,
                        as: 'Person',
                        attributes: ['id', 'name', 'gender', 'birthDate', 'generation'],
                        paranoid: false, // 允许查到软删除成员
                        required: false // 允许外键找不到
                    }
                ]
            });
            const parents = parentRelations.map(r => r.Person?.toJSON()).filter(Boolean);
            console.log(`【调试】找到 ${parents.length} 个父母`);

            // 2. 子女 (Correctly finds people who are children OF this person)
            console.log(`【调试】开始查询子女关系`);
            const childrenRelations = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: {
                    personId2: personId, // This person is the target of a "child" relationship
                    relationshipTypeId: { [Op.in]: [8, 9, 10, 11] } // 8:女儿, 9:儿子, 10:私生子, 11:私生女
                },
                include: [
                    {
                        model: Person,
                        as: 'Person', // The child is personId1
                        attributes: ['id', 'name', 'gender', 'birthDate', 'generation'],
                        paranoid: false, // 允许查到软删除成员
                        required: false // 允许外键找不到
                    }
                ]
            });
            const children = childrenRelations.map(r => r.Person?.toJSON()).filter(Boolean);
            console.log(`【调试】找到 ${children.length} 个子女`);

            // 3. 配偶 (Spouse)
            console.log(`【调试】开始查询配偶关系`);
            const spouseRelation = await PersonRelationship.findOne({
                paranoid: false, // 包含软删除的关系记录
                where: {
                    [Op.or]: [
                        { personId1: personId, relationshipTypeId: 5 },
                        { personId2: personId, relationshipTypeId: 5 }
                    ]
                },
                include: [
                    {
                        model: Person,
                        as: 'RelatedPerson',
                        attributes: ['id', 'name', 'gender', 'birthDate', 'generation'],
                        paranoid: false, // 允许查到软删除成员
                        required: false // 允许外键找不到
                    },
                    {
                        model: Person,
                        as: 'Person',
                        attributes: ['id', 'name', 'gender', 'birthDate', 'generation'],
                        paranoid: false, // 允许查到软删除成员
                        required: false // 允许外键找不到
                    }
                ]
            });
            let spouse = null;
            if (spouseRelation) {
                spouse = spouseRelation.personId1 === personId
                    ? spouseRelation.RelatedPerson?.toJSON()
                    : spouseRelation.Person?.toJSON();
                console.log(`【调试】找到配偶: ${spouse?.name}`);
            } else {
                console.log(`【调试】未找到配偶`);
            }

            // 4. 兄弟姐妹 (Correctly finds children of my parents, excluding myself)
            console.log(`【调试】开始查询兄弟姐妹关系`);
            let siblings = [];
            if (parents.length > 0) {
                const parentIds = parents.map(p => p.id);
                // Find all people who are children of my parents, but are not me.
                const siblingRelations = await PersonRelationship.findAll({
                    paranoid: false, // 包含软删除的关系记录
                    where: {
                        personId2: { [Op.in]: parentIds }, // Their parent is one of mine
                        relationshipTypeId: { [Op.in]: [8, 9, 10, 11] }, // They are a "child"
                        personId1: { [Op.ne]: personId } // and they are not me
                    },  
                    include: [
                        {
                            model: Person,
                            as: 'Person',
                            attributes: ['id', 'name', 'gender', 'birthDate', 'generation'],
                            paranoid: false, // 允许查到软删除成员
                            required: false // 允许外键找不到
                        }
                    ]
                });
                
                const siblingPojos = siblingRelations.map(r => r.Person?.toJSON()).filter(Boolean);
                // Remove duplicates in case of half-siblings being found via both parents
                siblings = Array.from(new Map(siblingPojos.map(item => [item.id, item])).values());
                console.log(`【调试】找到 ${siblings.length} 个兄弟姐妹`);
            }

            personJson.parents = parents;
            personJson.children = children;
            personJson.siblings = siblings;
            personJson.spouse = spouse;
            
            console.log(`【调试】成员详情获取完成`);
            return personJson;
            
        } catch (error) {
            console.error(`【错误】获取成员详情失败 ID: ${personId}`, error);
            console.error(`【错误】错误堆栈:`, error.stack);
            throw error;
        }
    }

    async createPerson(personData) {
        try {
            console.log('【调试】收到的personData:', personData);
            if (!personData.familyTreeId) {
                const defaultFamilyTree = await FamilyTree.findOne();
                personData.familyTreeId = defaultFamilyTree.id;
            }
            // 兜底处理日期字段
            if (personData.birthDate === '' || personData.birthDate === 'Invalid date') personData.birthDate = null;
            if (personData.deathDate === '' || personData.deathDate === 'Invalid date') personData.deathDate = null;
            const newPerson = await Person.create(personData);
            // 自动写入父母关系
            const PersonRelationship = (await import('./models/PersonRelationship.js')).default;
            const rels = [];
            if (personData.fatherId) {
                rels.push({ personId1: personData.fatherId, personId2: newPerson.id, relationshipTypeId: 1 }); // 1:父亲
            }
            if (personData.motherId) {
                rels.push({ personId1: personData.motherId, personId2: newPerson.id, relationshipTypeId: 4 }); // 4:母亲
            }
            if (personData.spouseId) {
                // 配偶关系是双向的
                rels.push({ personId1: newPerson.id, personId2: personData.spouseId, relationshipTypeId: 5 }); // 5:配偶
                rels.push({ personId1: personData.spouseId, personId2: newPerson.id, relationshipTypeId: 5 });
            }
            console.log('【调试】准备写入关系:', rels);
            if (rels.length > 0) {
                await PersonRelationship.bulkCreate(rels);
            }
            return newPerson;
        } catch (error) {
            console.error('创建成员出错:', error.message, error);
            throw error;
        }
    }

    async updatePerson(personId, personData) {
        try {
            console.log(`【调试】开始更新成员 ID: ${personId}`);
            console.log(`【调试】更新数据:`, personData);
            
            const person = await Person.findByPk(personId);
            if (!person) {
                console.log(`【调试】成员不存在 ID: ${personId}`);
                throw new Error('Person not found');
            }
            
            console.log(`【调试】找到成员: ${person.name} (ID: ${person.id})`);
            
            // 更新基本信息
            await person.update(personData);
            
            // 处理家庭关系更新
            const PersonRelationship = (await import('./models/PersonRelationship.js')).default;
            const { Op } = await import('sequelize');
            
            // 删除现有的关系记录
            await PersonRelationship.destroy({
                where: { 
                    [Op.or]: [
                        { personId1: personId },
                        { personId2: personId }
                    ]
                }
            });
            console.log(`【调试】已删除现有关系记录`);
            
            // 创建新的关系记录
            const rels = [];
            
            // 父亲关系
            if (personData.fatherId) {
                rels.push({ personId1: personData.fatherId, personId2: personId, relationshipTypeId: 1 }); // 1:父亲
                console.log(`【调试】添加父亲关系: ${personData.fatherId} -> ${personId}`);
            }
            
            // 母亲关系
            if (personData.motherId) {
                rels.push({ personId1: personData.motherId, personId2: personId, relationshipTypeId: 4 }); // 4:母亲
                console.log(`【调试】添加母亲关系: ${personData.motherId} -> ${personId}`);
            }
            
            // 养父关系
            if (personData.adoptiveFatherId || personData.adoptedFatherId) {
                const adoptedFatherId = personData.adoptiveFatherId || personData.adoptedFatherId;
                rels.push({ personId1: adoptedFatherId, personId2: personId, relationshipTypeId: 2 }); // 2:养父
                console.log(`【调试】添加养父关系: ${adoptedFatherId} -> ${personId}`);
            }
            
            // 养母关系
            if (personData.adoptiveMotherId || personData.adoptedMotherId) {
                const adoptedMotherId = personData.adoptiveMotherId || personData.adoptedMotherId;
                rels.push({ personId1: adoptedMotherId, personId2: personId, relationshipTypeId: 3 }); // 3:养母
                console.log(`【调试】添加养母关系: ${adoptedMotherId} -> ${personId}`);
            }
            
            // 配偶关系（双向）
            if (personData.spouseId) {
                rels.push({ personId1: personId, personId2: personData.spouseId, relationshipTypeId: 5 }); // 5:配偶
                rels.push({ personId1: personData.spouseId, personId2: personId, relationshipTypeId: 5 }); // 5:配偶
                console.log(`【调试】添加配偶关系: ${personId} <-> ${personData.spouseId}`);
            }
            
            // 创建关系记录
            if (rels.length > 0) {
                await PersonRelationship.bulkCreate(rels);
                console.log(`【调试】已创建 ${rels.length} 条关系记录`);
            } else {
                console.log(`【调试】没有关系记录需要创建`);
            }
            
            console.log(`【调试】成员更新完成`);
            return person;
            
        } catch (error) {
            console.error(`【错误】更新成员失败 ID: ${personId}`, error);
            throw error;
        }
    }

    async deletePerson(personId) {
        console.log(`【调试】开始删除成员 ID: ${personId}`);
        const person = await Person.findByPk(personId);
        if (!person) {
            console.log(`【调试】成员不存在 ID: ${personId}`);
            throw new Error('Person not found');
        }
        
        console.log(`【调试】找到成员: ${person.name} (ID: ${person.id})`);
        console.log(`【调试】删除前 deletedAt: ${person.deletedAt}`);
        
        // 软删除成员本身
        await person.destroy(); // 使用 destroy() 而不是 update() 来确保软删除
        
        console.log(`【调试】成员已软删除`);
        
        // 物理删除关系表（可选，或也可软删除）
        const deletedRelations = await PersonRelationship.destroy({
            where: { [Op.or]: [{ personId1: personId }, { personId2: personId }] }
        });
        
        console.log(`【调试】删除了 ${deletedRelations} 条关系记录`);
        
        return { message: 'Person soft deleted successfully' };
    }

    // 推导型亲属关系API
    async getRelatives(personId) {
        // 1. 获取本人
        const person = await Person.findByPk(personId);
        if (!person) return null;
        // 2. 获取父母
        const parentRels = await PersonRelationship.findAll({
            paranoid: false, // 包含软删除的关系记录
            where: { personId2: personId, relationshipTypeId: { [Op.in]: [1,2,3,4] } },
            include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
        });
        const parents = parentRels.map(r => r.Person.toJSON());
        // 3. 获取子女
        const childRels = await PersonRelationship.findAll({
            paranoid: false, // 包含软删除的关系记录
            where: { personId1: personId, relationshipTypeId: { [Op.in]: [8,9,10,11] } },
            include: [{ model: Person, as: 'RelatedPerson', attributes: ['id','name','gender','generation','birthDate'] }]
        });
        const children = childRels.map(r => r.RelatedPerson.toJSON());
        // 4. 获取兄弟姐妹（同父或同母，排除自己）
        let siblings = [];
        if (parents.length > 0) {
            const parentIds = parents.map(p => p.id);
            const siblingRels = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: {
                    personId2: { [Op.in]: parentIds },
                    relationshipTypeId: { [Op.in]: [8,9,10,11] },
                    personId1: { [Op.ne]: personId }
                },
                include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
            });
            const siblingPojos = siblingRels.map(r => r.Person.toJSON());
            siblings = Array.from(new Map(siblingPojos.map(item => [item.id, item])).values());
        }
        // 5. 获取祖父母（父母的父母）
        let grandparents = [];
        for (const parent of parents) {
            const gpRels = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: { personId2: parent.id, relationshipTypeId: { [Op.in]: [1,2,3,4] } },
                include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
            });
            grandparents.push(...gpRels.map(r => r.Person.toJSON()));
        }
        // 6. 获取外祖父母（母亲的父母）
        let maternalGrandparents = [];
        for (const parent of parents.filter(p=>p.gender==='女')) {
            const mgpRels = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: { personId2: parent.id, relationshipTypeId: { [Op.in]: [1,2,3,4] } },
                include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
            });
            maternalGrandparents.push(...mgpRels.map(r => r.Person.toJSON()));
        }
        // 7. 堂兄弟姐妹（父亲的其他子女，排除自己和同母兄弟姐妹）
        let paternalUnclesAunts = [];
        let cousins = [];
        for (const parent of parents.filter(p=>p.gender==='男')) {
            // 父亲的其他子女（我的兄弟姐妹+堂兄弟姐妹）
            const cousinRels = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: {
                    personId2: parent.id,
                    relationshipTypeId: { [Op.in]: [8,9,10,11] },
                    personId1: { [Op.ne]: personId }
                },
                include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
            });
            const cousinPojos = cousinRels.map(r => r.Person.toJSON());
            paternalUnclesAunts.push(...cousinPojos);
        }
        // 8. 表兄弟姐妹（母亲的其他子女，排除自己和同父兄弟姐妹）
        let maternalUnclesAunts = [];
        for (const parent of parents.filter(p=>p.gender==='女')) {
            const cousinRels = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: {
                    personId2: parent.id,
                    relationshipTypeId: { [Op.in]: [8,9,10,11] },
                    personId1: { [Op.ne]: personId }
                },
                include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
            });
            const cousinPojos = cousinRels.map(r => r.Person.toJSON());
            maternalUnclesAunts.push(...cousinPojos);
        }
        // 9. 配偶
        const spouseRels = await PersonRelationship.findAll({
            paranoid: false, // 包含软删除的关系记录
            where: {
                [Op.or]: [
                    { personId1: personId, relationshipTypeId: 5 },
                    { personId2: personId, relationshipTypeId: 5 }
                ]
            },
            include: [
                { model: Person, as: 'RelatedPerson', attributes: ['id','name','gender','generation','birthDate'] },
                { model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }
            ]
        });
        let spouses = [];
        for (const rel of spouseRels) {
            if (rel.personId1 === Number(personId)) {
                spouses.push(rel.RelatedPerson?.toJSON());
            } else {
                spouses.push(rel.Person?.toJSON());
            }
        }
        spouses = spouses.filter(Boolean);
        // 10. 继父母/养父母
        const stepParentRels = await PersonRelationship.findAll({
            paranoid: false, // 包含软删除的关系记录
            where: { personId2: personId, relationshipTypeId: { [Op.in]: [2,3] } },
            include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
        });
        const stepParents = stepParentRels.map(r => r.Person.toJSON());
        // 11. 继兄弟姐妹/养兄弟姐妹（继父母/养父母的其他子女，排除自己）
        let stepSiblings = [];
        for (const stepParent of stepParents) {
            const stepSiblingRels = await PersonRelationship.findAll({
                paranoid: false, // 包含软删除的关系记录
                where: {
                    personId2: stepParent.id,
                    relationshipTypeId: { [Op.in]: [8,9,10,11] },
                    personId1: { [Op.ne]: personId }
                },
                include: [{ model: Person, as: 'Person', attributes: ['id','name','gender','generation','birthDate'] }]
            });
            const stepSiblingPojos = stepSiblingRels.map(r => r.Person.toJSON());
            stepSiblings.push(...stepSiblingPojos);
        }
        // 去重
        function unique(arr) {
            return Array.from(new Map(arr.map(item => [item.id, item])).values());
        }
        return {
            parents: unique(parents),
            children: unique(children),
            siblings: unique(siblings),
            grandparents: unique(grandparents),
            maternalGrandparents: unique(maternalGrandparents),
            paternalCousins: unique(paternalUnclesAunts),
            maternalCousins: unique(maternalUnclesAunts),
            spouses: unique(spouses),
            stepParents: unique(stepParents),
            stepSiblings: unique(stepSiblings)
        };
    }
}

export default new PersonService(); 